import { getSignListAPI } from 'api'
import { useState, useEffect, useRef } from 'react'
import { Spin } from 'antd'
import styles from './index.module.scss'
import AnchorBar from 'components/AnchorBar'
import SignItem from 'components/SignItem'
import { useNavigate } from 'react-router-dom'

type PropsType = Partial<{ keywords: string }>

export default function SignContent({ keywords }: PropsType) {
  const [categorySignList, setCategorySignList] = useState<Category[]>([])
  const [loading, setLoading] = useState(false)
  const signContentRef = useRef<HTMLDivElement>()
  const navigate = useNavigate()

  // 获取符号集合
  const getCategorySignList = async (keywords?: string) => {
    setLoading(true)
    try {
      const data = await getSignListAPI(keywords)
      setCategorySignList(data)
    } catch (err) {
      console.warn(err)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    getCategorySignList(keywords)
  }, [keywords])

  return (
    <div className={styles['sign-content']} ref={signContentRef as React.LegacyRef<HTMLDivElement>}>
      <AnchorBar list={categorySignList} container={signContentRef.current} />
      <Spin tip='Loading...' size='large' style={{ marginTop: '25%' }} spinning={loading}>
        <ul>
          {categorySignList.map(item => (
            <li key={item.id}>
              <h2 className='category-type' id={`${item.categoryNameEn}`}>
                {item.categoryNameZh}（{item.children?.length}）
              </h2>
              <div>
                {item.children!.map(v => (
                  <SignItem key={v.id} signInfo={v} navigate={navigate} />
                ))}
              </div>
            </li>
          ))}
        </ul>
      </Spin>
    </div>
  )
}
